package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiangyao.common.exception.ServerException;
import com.jiangyao.dao.IClassUserDao;
import com.jiangyao.model.dto.ClassUserDto;
import com.jiangyao.model.dto.backend.OrgClassApplyDTO;
import com.jiangyao.model.dto.backend.OrgClassApplyListDTO;
import com.jiangyao.model.entity.ClassUser;
import com.jiangyao.model.entity.OrgClassApply;
import com.jiangyao.dao.IOrgClassApplyDao;
import com.jiangyao.model.vo.AdminUserSessionVO;
import com.jiangyao.model.vo.backend.ClassInfoListVO;
import com.jiangyao.model.vo.backend.OrgClassApplyListVO;
import com.jiangyao.model.vo.backend.OrgInfoClassUserExcelVO;
import com.jiangyao.service.OrgClassApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 组织班级成员申请表 服务实现类
 * </p>
 *
 * @author xiangyan
 * @since 2020-08-15
 */
@Service
public class OrgClassApplyServiceImpl extends BaseServiceImpl<IOrgClassApplyDao, OrgClassApply> implements OrgClassApplyService {
    @Autowired
    private IClassUserDao classUserDao ;

    @Autowired
    private DozerBeanMapper dozerBeanMapper;

    @Autowired
    private IOrgClassApplyDao orgClassApplyDao;

    @Override
    public Boolean applyForOrg(ClassUserDto classUserDto) {
        QueryWrapper<ClassUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", classUserDto.getOrgId()).eq("user_id",classUserDto.getUserId())
                .eq("class_id",classUserDto.getClassId()).eq("status",1);
        queryWrapper.last(" LIMIT 1");
        ClassUser exist = classUserDao.selectOne(queryWrapper);
        if (exist != null) {
            throw new ServerException(303, "已是该组织的成员");
        }

        QueryWrapper<OrgClassApply> applyQueryWrapper = new QueryWrapper<>();
        applyQueryWrapper.eq("org_id", classUserDto.getOrgId()).eq("user_id",classUserDto.getUserId())
                .eq("class_id",classUserDto.getClassId()).eq("status",1);
        applyQueryWrapper.last(" LIMIT 1");
        OrgClassApply existApply = this.getOne(applyQueryWrapper);
        if (existApply != null) {
            throw new ServerException(304, "已申请过该组织,待审核中");
        }

        OrgClassApply apply = dozerBeanMapper.map(classUserDto, OrgClassApply.class);
        apply.setApplyTime(new Date());
        apply.setStatus(1);
        apply.setApplyType(2);
        this.save(apply);
        return true;
    }

    @Override
    public List<OrgClassApplyListVO> getApiList(OrgClassApplyListDTO listPageDTO) {
        listPageDTO.setUserId(getLoginApiUserId());
       return orgClassApplyDao.getApiList(listPageDTO);
    }

    @Override
    public Page<OrgClassApplyListVO> getListPage(OrgClassApplyListDTO listPageDTO) {
        // 登录用户信息
        AdminUserSessionVO adminUserSessionVO = getAdminLoginSession();
        // 当前登录用户管理的组织ID集合(业务数据权限)
        listPageDTO.setOrgIdList(adminUserSessionVO.getOrgIdList());
        // 当前登录用户管理的班级ID集合(业务数据权限)
        listPageDTO.setClassIdList(adminUserSessionVO.getClassIdList());

        Page<OrgClassApplyListVO> page = new Page<>(listPageDTO.getPageNo(), listPageDTO.getPageSize());
        orgClassApplyDao.getListPage(page, listPageDTO);
        return page;
    }

    @Override
    public void doAudit(OrgClassApplyDTO applyDTO) {
        QueryWrapper<OrgClassApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", applyDTO.getApplyIdList());
        queryWrapper.eq("status", 1);
        // 待审核申请数量
        int waitAuditCount = this.count(queryWrapper);
        // 本次审核记录数量与待审核数量不一致
        if (applyDTO.getApplyIdList().size() != waitAuditCount) {
            throw new ServerException(100, "申请记录不是待审核状态");
        }
        UpdateWrapper<OrgClassApply> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", applyDTO.getApplyIdList());
        updateWrapper.set("status", applyDTO.getStatus());
        updateWrapper.set("remark", applyDTO.getRemark());
        updateWrapper.set("audit_time", new Date());
        updateWrapper.set("audit_admin_id", getLoginAdminUserId());
        this.update(updateWrapper);
        // 拒绝申请，直接返回
        if(applyDTO.getStatus()==3){
            return ;
        }
        // 同意申请，写入class_user
        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", applyDTO.getApplyIdList());
        queryWrapper.select("org_id", "class_id", "user_id");
        List<OrgClassApply> applyList = this.list(queryWrapper);
        // 班级成员集合
        List<ClassUser> classUserList = new ArrayList<>(applyList.size());
        // 组织ID + "-" + 班级ID + "-" + 用户ID
        List<String> orgClassUserIdList = new ArrayList<>(applyList.size());
        Integer adminUserId = getLoginAdminUserId();
        applyList.forEach(apply -> {
            ClassUser classUser = dozerBeanMapper.map(apply, ClassUser.class);
            classUser.setCreateAdminId(adminUserId);
            classUser.setApplyType(2);
            classUserList.add(classUser);
            String orgClassUserId = classUser.getOrgId() + "_" + classUser.getClassId() + "_" + classUser.getUserId();
            orgClassUserIdList.add(orgClassUserId);
        });
        // 将以前已经导入用户，状态修改为正常
        classUserDao.updateStatus(orgClassUserIdList, adminUserId, 1);
        // 批量保存
        classUserDao.insertBatch(classUserList);
    }
}
